import { WEBSOCKETS, toSuccess, useEntityManager } from "@sker/core";
import { useData } from "@sker/runtime";
import { InjectionToken, container } from "tsyringe";
import { z } from "zod";

export default async () => {
    const input = z.object({
        id: z.string(),
        code: z.string()
    });
    const body = input.parse(useData());
    const count = await useEntityManager(async m => {
        const websockets = container.resolve(WEBSOCKETS);
        const list = await Promise.all([...websockets.values()].map(wss => {
            return new Promise<number>((resolve, reject) => {
                wss.send(JSON.stringify({
                    type: CLOUD_CODE,
                    payload: {
                        id: body.id,
                        code: body?.code,
                        type: 'script'
                    }
                }), err => {
                    if (err) return resolve(0)
                    return resolve(1)
                })
            })
        }));
        if (list && list.length > 0) {
            return list.reduce((a, b) => a + b)
        }
        return 0;
    })
    return toSuccess(count)
}
interface ICloudCode {
    id: string;
    code: string;
    timeout?: number;
}
const CLOUD_CODE: InjectionToken<ICloudCode> = `CLOUD_CODE`
